DonorsChoose

DonorsChoose.org receives hundreds of thousands of project proposals each year for classroom projects in need of funding. Right now, a large number of volunteers is needed to manually screen each submission before it's approved to be posted on the DonorsChoose.org website.

Next year, DonorsChoose.org expects to receive close to 500,000 project proposals. As a result, there are three main problems they need to solve:

  • How to scale current manual processes and resources to screen 500,000 projects so that they can be posted as quickly and as efficiently as possible
  • How to increase the consistency of project vetting across different volunteers to improve the experience for teachers
  • How to focus volunteer time on the applications that need the most assistance

The goal of the competition is to predict whether or not a DonorsChoose.org project proposal submitted by a teacher will be approved, using the text of project descriptions as well as additional metadata about the project, teacher, and school. DonorsChoose.org can then use this information to identify projects most likely to need further review before approval.

About the DonorsChoose Data Set

The train.csv data set provided by DonorsChoose contains the following features:

Feature Description
project_id A unique identifier for the proposed project. Example: p036502
project_title Title of the project. Examples:
  • Art Will Make You Happy!
  • First Grade Fun
project_grade_category Grade level of students for which the project is targeted. One of the following enumerated values:
  • Grades PreK-2
  • Grades 3-5
  • Grades 6-8
  • Grades 9-12
project_subject_categories One or more (comma-separated) subject categories for the project from the following enumerated list of values:
  • Applied Learning
  • Care & Hunger
  • Health & Sports
  • History & Civics
  • Literacy & Language
  • Math & Science
  • Music & The Arts
  • Special Needs
  • Warmth

Examples:
  • Music & The Arts
  • Literacy & Language, Math & Science
school_state State where school is located (Two-letter U.S. postal code). Example: WY
project_subject_subcategories One or more (comma-separated) subject subcategories for the project. Examples:
  • Literacy
  • Literature & Writing, Social Sciences
project_resource_summary An explanation of the resources needed for the project. Example:
  • My students need hands on literacy materials to manage sensory needs!
project_essay_1 First application essay*
project_essay_2 Second application essay*
project_essay_3 Third application essay*
project_essay_4 Fourth application essay*
project_submitted_datetime Datetime when project application was submitted. Example: 2016-04-28 12:43:56.245
teacher_id A unique identifier for the teacher of the proposed project. Example: bdf8baa8fedef6bfeec7ae4ff1c15c56
teacher_prefix Teacher's title. One of the following enumerated values:
  • nan
  • Dr.
  • Mr.
  • Mrs.
  • Ms.
  • Teacher.
teacher_number_of_previously_posted_projects Number of project applications previously submitted by the same teacher. Example: 2

* See the section Notes on the Essay Data for more details about these features.

Additionally, the resources.csv data set provides more data about the resources required for each project. Each line in this file represents a resource required by a project:

Feature Description
id A project_id value from the train.csv file. Example: p036502
description Desciption of the resource. Example: Tenor Saxophone Reeds, Box of 25
quantity Quantity of the resource required. Example: 3
price Price of the resource required. Example: 9.95

Note: Many projects require multiple resources. The id value corresponds to a project_id in train.csv, so you use it as a key to retrieve all resources needed for a project:

The data set contains the following label (the value you will attempt to predict):

Label Description
project_is_approved A binary flag indicating whether DonorsChoose approved the project. A value of 0 indicates the project was not approved, and a value of 1 indicates the project was approved.

Notes on the Essay Data

    Prior to May 17, 2016, the prompts for the essays were as follows:
  • __project_essay_1:__ "Introduce us to your classroom"
  • __project_essay_2:__ "Tell us more about your students"
  • __project_essay_3:__ "Describe how your students will use the materials you're requesting"
  • __project_essay_3:__ "Close by sharing why your project will make a difference"
    Starting on May 17, 2016, the number of essays was reduced from 4 to 2, and the prompts for the first 2 essays were changed to the following:
  • __project_essay_1:__ "Describe your students: What makes your students special? Specific details about their background, your neighborhood, and your school are all helpful."
  • __project_essay_2:__ "About your project: How will these materials make a difference in your students' learning and improve their school lives?"

  • For all projects with project_submitted_datetime of 2016-05-17 and later, the values of project_essay_3 and project_essay_4 will be NaN.
In [1]:
%%time

%matplotlib inline
import warnings
warnings.filterwarnings("ignore")

import sqlite3
import math
import pandas as pd
import numpy as np
import nltk
import string
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import confusion_matrix
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
from nltk.stem.porter import PorterStemmer

import re
# Tutorial about Python regular expressions: https://pymotw.com/2/re/
import string
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer

from gensim.models import Word2Vec
from gensim.models import KeyedVectors
import pickle

from tqdm import tqdm
import os

from plotly import plotly
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()
from collections import Counter
Wall time: 55 s

1.1 Reading Data

In [2]:
# using 35000 rows due to memory constraint

project_data = pd.read_csv('train_data.csv',nrows=35000)
resource_data = pd.read_csv('resources.csv')
In [3]:
print("Number of data points in train data", project_data.shape)
print('-'*50)
print("The attributes of data :", project_data.columns.values)
Number of data points in train data (35000, 17)
--------------------------------------------------
The attributes of data : ['Unnamed: 0' 'id' 'teacher_id' 'teacher_prefix' 'school_state'
 'project_submitted_datetime' 'project_grade_category'
 'project_subject_categories' 'project_subject_subcategories'
 'project_title' 'project_essay_1' 'project_essay_2' 'project_essay_3'
 'project_essay_4' 'project_resource_summary'
 'teacher_number_of_previously_posted_projects' 'project_is_approved']
In [4]:
print("Number of data points in train data", resource_data.shape)
print(resource_data.columns.values)
resource_data.head(2)
Number of data points in train data (1541272, 4)
['id' 'description' 'quantity' 'price']
Out[4]:
id description quantity price
0 p233245 LC652 - Lakeshore Double-Space Mobile Drying Rack 1 149.00
1 p069063 Bouncy Bands for Desks (Blue support pipes) 3 14.95

1.2 preprocessing of project_subject_categories

In [5]:
catogories = list(project_data['project_subject_categories'].values)
# remove special characters from list of strings python: https://stackoverflow.com/a/47301924/4084039

# https://www.geeksforgeeks.org/removing-stop-words-nltk-python/
# https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string
# https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python
cat_list = []
for i in catogories:
    temp = ""
    # consider we have text like this "Math & Science, Warmth, Care & Hunger"
    for j in i.split(','): # it will split it in three parts ["Math & Science", "Warmth", "Care & Hunger"]
        if 'The' in j.split(): # this will split each of the catogory based on space "Math & Science"=> "Math","&", "Science"
            j=j.replace('The','') # if we have the words "The" we are going to replace it with ''(i.e removing 'The')
        j = j.replace(' ','') # we are placeing all the ' '(space) with ''(empty) ex:"Math & Science"=>"Math&Science"
        temp+=j.strip()+" " #" abc ".strip() will return "abc", remove the trailing spaces
        temp = temp.replace('&','_') # we are replacing the & value into 
    cat_list.append(temp.strip())
    
project_data['clean_categories'] = cat_list
project_data.drop(['project_subject_categories'], axis=1, inplace=True)

from collections import Counter
my_counter = Counter()
for word in project_data['clean_categories'].values:
    my_counter.update(word.split())

cat_dict = dict(my_counter)
sorted_cat_dict = dict(sorted(cat_dict.items(), key=lambda kv: kv[1]))

1.3 preprocessing of project_subject_subcategories

In [6]:
sub_catogories = list(project_data['project_subject_subcategories'].values)
# remove special characters from list of strings python: https://stackoverflow.com/a/47301924/4084039

# https://www.geeksforgeeks.org/removing-stop-words-nltk-python/
# https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string
# https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python

sub_cat_list = []
for i in sub_catogories:
    temp = ""
    # consider we have text like this "Math & Science, Warmth, Care & Hunger"
    for j in i.split(','): # it will split it in three parts ["Math & Science", "Warmth", "Care & Hunger"]
        if 'The' in j.split(): # this will split each of the catogory based on space "Math & Science"=> "Math","&", "Science"
            j=j.replace('The','') # if we have the words "The" we are going to replace it with ''(i.e removing 'The')
        j = j.replace(' ','') # we are placeing all the ' '(space) with ''(empty) ex:"Math & Science"=>"Math&Science"
        temp +=j.strip()+" "#" abc ".strip() will return "abc", remove the trailing spaces
        temp = temp.replace('&','_')
    sub_cat_list.append(temp.strip())

project_data['clean_subcategories'] = sub_cat_list
project_data.drop(['project_subject_subcategories'], axis=1, inplace=True)

# count of all the words in corpus python: https://stackoverflow.com/a/22898595/4084039
my_counter = Counter()
for word in project_data['clean_subcategories'].values:
    my_counter.update(word.split())
    
sub_cat_dict = dict(my_counter)
sorted_sub_cat_dict = dict(sorted(sub_cat_dict.items(), key=lambda kv: kv[1]))

1.3 Text preprocessing

In [7]:
# merge two column text dataframe: 
project_data["essay"] = project_data["project_essay_1"].map(str) +\
                        project_data["project_essay_2"].map(str) + \
                        project_data["project_essay_3"].map(str) + \
                        project_data["project_essay_4"].map(str)
In [8]:
project_data.head(2)
Out[8]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 project_essay_3 project_essay_4 project_resource_summary teacher_number_of_previously_posted_projects project_is_approved clean_categories clean_subcategories essay
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs. IN 2016-12-05 13:43:57 Grades PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... NaN NaN My students need opportunities to practice beg... 0 0 Literacy_Language ESL Literacy My students are English learners that are work...
1 140945 p258326 897464ce9ddc600bced1151f324dd63a Mr. FL 2016-10-25 09:22:10 Grades 6-8 Wanted: Projector for Hungry Learners Our students arrive to our school eager to lea... The projector we need for our school is very c... NaN NaN My students need a projector to help with view... 7 1 History_Civics Health_Sports Civics_Government TeamSports Our students arrive to our school eager to lea...
In [9]:
#### 1.4.2.3 Using Pretrained Models: TFIDF weighted W2V
In [10]:
# printing some random reviews
print(project_data['essay'].values[0])
print("="*50)
print(project_data['essay'].values[150])
print("="*50)
print(project_data['essay'].values[1000])
print("="*50)
print(project_data['essay'].values[20000])
print("="*50)
My students are English learners that are working on English as their second or third languages. We are a melting pot of refugees, immigrants, and native-born Americans bringing the gift of language to our school. \r\n\r\n We have over 24 languages represented in our English Learner program with students at every level of mastery.  We also have over 40 countries represented with the families within our school.  Each student brings a wealth of knowledge and experiences to us that open our eyes to new cultures, beliefs, and respect.\"The limits of your language are the limits of your world.\"-Ludwig Wittgenstein  Our English learner's have a strong support system at home that begs for more resources.  Many times our parents are learning to read and speak English along side of their children.  Sometimes this creates barriers for parents to be able to help their child learn phonetics, letter recognition, and other reading skills.\r\n\r\nBy providing these dvd's and players, students are able to continue their mastery of the English language even if no one at home is able to assist.  All families with students within the Level 1 proficiency status, will be a offered to be a part of this program.  These educational videos will be specially chosen by the English Learner Teacher and will be sent home regularly to watch.  The videos are to help the child develop early reading skills.\r\n\r\nParents that do not have access to a dvd player will have the opportunity to check out a dvd player to use for the year.  The plan is to use these videos and educational dvd's for the years to come for other EL students.\r\nnannan
==================================================
The 51 fifth grade students that will cycle through my classroom this year all love learning, at least most of the time. At our school, 97.3% of the students receive free or reduced price lunch. Of the 560 students, 97.3% are minority students. \r\nThe school has a vibrant community that loves to get together and celebrate. Around Halloween there is a whole school parade to show off the beautiful costumes that students wear. On Cinco de Mayo we put on a big festival with crafts made by the students, dances, and games. At the end of the year the school hosts a carnival to celebrate the hard work put in during the school year, with a dunk tank being the most popular activity.My students will use these five brightly colored Hokki stools in place of regular, stationary, 4-legged chairs. As I will only have a total of ten in the classroom and not enough for each student to have an individual one, they will be used in a variety of ways. During independent reading time they will be used as special chairs students will each use on occasion. I will utilize them in place of chairs at my small group tables during math and reading times. The rest of the day they will be used by the students who need the highest amount of movement in their life in order to stay focused on school.\r\n\r\nWhenever asked what the classroom is missing, my students always say more Hokki Stools. They can't get their fill of the 5 stools we already have. When the students are sitting in group with me on the Hokki Stools, they are always moving, but at the same time doing their work. Anytime the students get to pick where they can sit, the Hokki Stools are the first to be taken. There are always students who head over to the kidney table to get one of the stools who are disappointed as there are not enough of them. \r\n\r\nWe ask a lot of students to sit for 7 hours a day. The Hokki stools will be a compromise that allow my students to do desk work and move at the same time. These stools will help students to meet their 60 minutes a day of movement by allowing them to activate their core muscles for balance while they sit. For many of my students, these chairs will take away the barrier that exists in schools for a child who can't sit still.nannan
==================================================
How do you remember your days of school? Was it in a sterile environment with plain walls, rows of desks, and a teacher in front of the room? A typical day in our room is nothing like that. I work hard to create a warm inviting themed room for my students look forward to coming to each day.\r\n\r\nMy class is made up of 28 wonderfully unique boys and girls of mixed races in Arkansas.\r\nThey attend a Title I school, which means there is a high enough percentage of free and reduced-price lunch to qualify. Our school is an \"open classroom\" concept, which is very unique as there are no walls separating the classrooms. These 9 and 10 year-old students are very eager learners; they are like sponges, absorbing all the information and experiences and keep on wanting more.With these resources such as the comfy red throw pillows and the whimsical nautical hanging decor and the blue fish nets, I will be able to help create the mood in our classroom setting to be one of a themed nautical environment. Creating a classroom environment is very important in the success in each and every child's education. The nautical photo props will be used with each child as they step foot into our classroom for the first time on Meet the Teacher evening. I'll take pictures of each child with them, have them developed, and then hung in our classroom ready for their first day of 4th grade.  This kind gesture will set the tone before even the first day of school! The nautical thank you cards will be used throughout the year by the students as they create thank you cards to their team groups.\r\n\r\nYour generous donations will help me to help make our classroom a fun, inviting, learning environment from day one.\r\n\r\nIt costs lost of money out of my own pocket on resources to get our classroom ready. Please consider helping with this project to make our new school year a very successful one. Thank you!nannan
==================================================
My kindergarten students have varied disabilities ranging from speech and language delays, cognitive delays, gross/fine motor delays, to autism. They are eager beavers and always strive to work their hardest working past their limitations. \r\n\r\nThe materials we have are the ones I seek out for my students. I teach in a Title I school where most of the students receive free or reduced price lunch.  Despite their disabilities and limitations, my students love coming to school and come eager to learn and explore.Have you ever felt like you had ants in your pants and you needed to groove and move as you were in a meeting? This is how my kids feel all the time. The want to be able to move as they learn or so they say.Wobble chairs are the answer and I love then because they develop their core, which enhances gross motor and in Turn fine motor skills. \r\nThey also want to learn through games, my kids don't want to sit and do worksheets. They want to learn to count by jumping and playing. Physical engagement is the key to our success. The number toss and color and shape mats can make that happen. My students will forget they are doing work and just have the fun a 6 year old deserves.nannan
==================================================
In [11]:
# https://stackoverflow.com/a/47091490/4084039
import re

def decontracted(phrase):
    # specific
    phrase = re.sub(r"won't", "will not", phrase)
    phrase = re.sub(r"can\'t", "can not", phrase)

    # general
    phrase = re.sub(r"n\'t", " not", phrase)
    phrase = re.sub(r"\'re", " are", phrase)
    phrase = re.sub(r"\'s", " is", phrase)
    phrase = re.sub(r"\'d", " would", phrase)
    phrase = re.sub(r"\'ll", " will", phrase)
    phrase = re.sub(r"\'t", " not", phrase)
    phrase = re.sub(r"\'ve", " have", phrase)
    phrase = re.sub(r"\'m", " am", phrase)
    return phrase
In [12]:
sent = decontracted(project_data['essay'].values[20000])
print(sent)
print("="*50)
My kindergarten students have varied disabilities ranging from speech and language delays, cognitive delays, gross/fine motor delays, to autism. They are eager beavers and always strive to work their hardest working past their limitations. \r\n\r\nThe materials we have are the ones I seek out for my students. I teach in a Title I school where most of the students receive free or reduced price lunch.  Despite their disabilities and limitations, my students love coming to school and come eager to learn and explore.Have you ever felt like you had ants in your pants and you needed to groove and move as you were in a meeting? This is how my kids feel all the time. The want to be able to move as they learn or so they say.Wobble chairs are the answer and I love then because they develop their core, which enhances gross motor and in Turn fine motor skills. \r\nThey also want to learn through games, my kids do not want to sit and do worksheets. They want to learn to count by jumping and playing. Physical engagement is the key to our success. The number toss and color and shape mats can make that happen. My students will forget they are doing work and just have the fun a 6 year old deserves.nannan
==================================================
In [13]:
# \r \n \t remove from string python: http://texthandler.com/info/remove-line-breaks-python/
sent = sent.replace('\\r', ' ')
sent = sent.replace('\\"', ' ')
sent = sent.replace('\\n', ' ')
print(sent)
My kindergarten students have varied disabilities ranging from speech and language delays, cognitive delays, gross/fine motor delays, to autism. They are eager beavers and always strive to work their hardest working past their limitations.     The materials we have are the ones I seek out for my students. I teach in a Title I school where most of the students receive free or reduced price lunch.  Despite their disabilities and limitations, my students love coming to school and come eager to learn and explore.Have you ever felt like you had ants in your pants and you needed to groove and move as you were in a meeting? This is how my kids feel all the time. The want to be able to move as they learn or so they say.Wobble chairs are the answer and I love then because they develop their core, which enhances gross motor and in Turn fine motor skills.   They also want to learn through games, my kids do not want to sit and do worksheets. They want to learn to count by jumping and playing. Physical engagement is the key to our success. The number toss and color and shape mats can make that happen. My students will forget they are doing work and just have the fun a 6 year old deserves.nannan
In [14]:
#remove spacial character: https://stackoverflow.com/a/5843547/4084039
sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
print(sent)
My kindergarten students have varied disabilities ranging from speech and language delays cognitive delays gross fine motor delays to autism They are eager beavers and always strive to work their hardest working past their limitations The materials we have are the ones I seek out for my students I teach in a Title I school where most of the students receive free or reduced price lunch Despite their disabilities and limitations my students love coming to school and come eager to learn and explore Have you ever felt like you had ants in your pants and you needed to groove and move as you were in a meeting This is how my kids feel all the time The want to be able to move as they learn or so they say Wobble chairs are the answer and I love then because they develop their core which enhances gross motor and in Turn fine motor skills They also want to learn through games my kids do not want to sit and do worksheets They want to learn to count by jumping and playing Physical engagement is the key to our success The number toss and color and shape mats can make that happen My students will forget they are doing work and just have the fun a 6 year old deserves nannan
In [15]:
# https://gist.github.com/sebleier/554280
# we are removing the words from the stop words list: 'no', 'nor', 'not'
stopwords= ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've",\
            "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', \
            'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their',\
            'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', \
            'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', \
            'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', \
            'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',\
            'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further',\
            'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more',\
            'most', 'other', 'some', 'such', 'only', 'own', 'same', 'so', 'than', 'too', 'very', \
            's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', \
            've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn',\
            "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn',\
            "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", \
            'won', "won't", 'wouldn', "wouldn't"]
In [16]:
# Combining all the above stundents 
from tqdm import tqdm
preprocessed_essays = []
# tqdm is for printing the status bar
for sentance in tqdm(project_data['essay'].values):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    # https://gist.github.com/sebleier/554280
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    preprocessed_essays.append(sent.lower().strip())
project_data['preprocessed_essays'] = preprocessed_essays
100%|██████████████████████████████████████████████████████████████████████████| 35000/35000 [00:29<00:00, 1194.43it/s]
In [17]:
# after preprocesing
preprocessed_essays[20000]
Out[17]:
'my kindergarten students varied disabilities ranging speech language delays cognitive delays gross fine motor delays autism they eager beavers always strive work hardest working past limitations the materials ones i seek students i teach title i school students receive free reduced price lunch despite disabilities limitations students love coming school come eager learn explore have ever felt like ants pants needed groove move meeting this kids feel time the want able move learn say wobble chairs answer i love develop core enhances gross motor turn fine motor skills they also want learn games kids not want sit worksheets they want learn count jumping playing physical engagement key success the number toss color shape mats make happen my students forget work fun 6 year old deserves nannan'

Number of words in combined Essay

In [18]:
proj_essay_wrd_count = []

for word in project_data['preprocessed_essays']:
    proj_essay_wrd_count.append(len(word.split()))
project_data['proj_essay_wrd_count'] = proj_essay_wrd_count

project_data.head(3)
Out[18]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 project_essay_3 project_essay_4 project_resource_summary teacher_number_of_previously_posted_projects project_is_approved clean_categories clean_subcategories essay preprocessed_essays proj_essay_wrd_count
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs. IN 2016-12-05 13:43:57 Grades PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... NaN NaN My students need opportunities to practice beg... 0 0 Literacy_Language ESL Literacy My students are English learners that are work... my students english learners working english s... 161
1 140945 p258326 897464ce9ddc600bced1151f324dd63a Mr. FL 2016-10-25 09:22:10 Grades 6-8 Wanted: Projector for Hungry Learners Our students arrive to our school eager to lea... The projector we need for our school is very c... NaN NaN My students need a projector to help with view... 7 1 History_Civics Health_Sports Civics_Government TeamSports Our students arrive to our school eager to lea... our students arrive school eager learn they po... 109
2 21895 p182444 3465aaf82da834c0582ebd0ef8040ca0 Ms. AZ 2016-08-31 12:03:56 Grades 6-8 Soccer Equipment for AWESOME Middle School Stu... \r\n\"True champions aren't always the ones th... The students on the campus come to school know... NaN NaN My students need shine guards, athletic socks,... 1 0 Health_Sports Health_Wellness TeamSports \r\n\"True champions aren't always the ones th... true champions not always ones win guts by mia... 202

1.4 Preprocessing of `project_title`

In [19]:
# similarly you can preprocess the titles also
# printing some random essays.
print(project_data['project_title'].values[0])
print("="*50)
print(project_data['project_title'].values[150])
print("="*50)
print(project_data['project_title'].values[1000])
Educational Support for English Learners at Home
==================================================
More Movement with Hokki Stools
==================================================
Sailing Into a Super 4th Grade Year
In [22]:
# Combining all the above statemennts 
from tqdm import tqdm
preprocessed_titles = []
# tqdm is for printing the status bar
for sentance in tqdm(project_data['project_title'].values):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    # https://gist.github.com/sebleier/554280
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    preprocessed_titles.append(sent.lower().strip())
project_data['preprocessed_titles'] = preprocessed_titles
100%|█████████████████████████████████████████████████████████████████████████| 35000/35000 [00:01<00:00, 25632.89it/s]
In [23]:
project_data.head(3)
Out[23]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 ... project_essay_4 project_resource_summary teacher_number_of_previously_posted_projects project_is_approved clean_categories clean_subcategories essay preprocessed_essays proj_essay_wrd_count preprocessed_titles
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs. IN 2016-12-05 13:43:57 Grades PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... ... NaN My students need opportunities to practice beg... 0 0 Literacy_Language ESL Literacy My students are English learners that are work... my students english learners working english s... 161 educational support english learners home
1 140945 p258326 897464ce9ddc600bced1151f324dd63a Mr. FL 2016-10-25 09:22:10 Grades 6-8 Wanted: Projector for Hungry Learners Our students arrive to our school eager to lea... The projector we need for our school is very c... ... NaN My students need a projector to help with view... 7 1 History_Civics Health_Sports Civics_Government TeamSports Our students arrive to our school eager to lea... our students arrive school eager learn they po... 109 wanted projector hungry learners
2 21895 p182444 3465aaf82da834c0582ebd0ef8040ca0 Ms. AZ 2016-08-31 12:03:56 Grades 6-8 Soccer Equipment for AWESOME Middle School Stu... \r\n\"True champions aren't always the ones th... The students on the campus come to school know... ... NaN My students need shine guards, athletic socks,... 1 0 Health_Sports Health_Wellness TeamSports \r\n\"True champions aren't always the ones th... true champions not always ones win guts by mia... 202 soccer equipment awesome middle school students

3 rows × 21 columns

Number of words in project title

In [24]:
proj_title_wrd_count = []

for word in project_data['preprocessed_titles']:
    proj_title_wrd_count.append(len(word.split()))
project_data['proj_title_wrd_count'] = proj_title_wrd_count
project_data.head(3)
Out[24]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 ... project_resource_summary teacher_number_of_previously_posted_projects project_is_approved clean_categories clean_subcategories essay preprocessed_essays proj_essay_wrd_count preprocessed_titles proj_title_wrd_count
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs. IN 2016-12-05 13:43:57 Grades PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... ... My students need opportunities to practice beg... 0 0 Literacy_Language ESL Literacy My students are English learners that are work... my students english learners working english s... 161 educational support english learners home 5
1 140945 p258326 897464ce9ddc600bced1151f324dd63a Mr. FL 2016-10-25 09:22:10 Grades 6-8 Wanted: Projector for Hungry Learners Our students arrive to our school eager to lea... The projector we need for our school is very c... ... My students need a projector to help with view... 7 1 History_Civics Health_Sports Civics_Government TeamSports Our students arrive to our school eager to lea... our students arrive school eager learn they po... 109 wanted projector hungry learners 4
2 21895 p182444 3465aaf82da834c0582ebd0ef8040ca0 Ms. AZ 2016-08-31 12:03:56 Grades 6-8 Soccer Equipment for AWESOME Middle School Stu... \r\n\"True champions aren't always the ones th... The students on the campus come to school know... ... My students need shine guards, athletic socks,... 1 0 Health_Sports Health_Wellness TeamSports \r\n\"True champions aren't always the ones th... true champions not always ones win guts by mia... 202 soccer equipment awesome middle school students 6

3 rows × 22 columns

In [25]:
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer

neg = []
pos = []
neu = []
compound = []

sid = SentimentIntensityAnalyzer()

for for_sentiment  in tqdm(project_data['preprocessed_essays']):

    neg.append(sid.polarity_scores(for_sentiment)['neg']) #Negative Sentiment score
    pos.append(sid.polarity_scores(for_sentiment)['pos']) #Positive Sentiment score
    neu.append(sid.polarity_scores(for_sentiment)['neu']) #Neutral Sentiment score
    compound.append(sid.polarity_scores(for_sentiment)['compound']) #Compound Sentiment score

# Creating new features    
project_data['Essay_neg_ss']      = neg
project_data['Essay_pos_ss']      = pos
project_data['Essay_neu_ss']      = neu
project_data['Essay_compound_ss'] = compound

project_data.head(3)
100%|████████████████████████████████████████████████████████████████████████████| 35000/35000 [06:19<00:00, 92.34it/s]
Out[25]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 ... clean_subcategories essay preprocessed_essays proj_essay_wrd_count preprocessed_titles proj_title_wrd_count Essay_neg_ss Essay_pos_ss Essay_neu_ss Essay_compound_ss
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs. IN 2016-12-05 13:43:57 Grades PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... ... ESL Literacy My students are English learners that are work... my students english learners working english s... 161 educational support english learners home 5 0.012 0.144 0.844 0.9694
1 140945 p258326 897464ce9ddc600bced1151f324dd63a Mr. FL 2016-10-25 09:22:10 Grades 6-8 Wanted: Projector for Hungry Learners Our students arrive to our school eager to lea... The projector we need for our school is very c... ... Civics_Government TeamSports Our students arrive to our school eager to lea... our students arrive school eager learn they po... 109 wanted projector hungry learners 4 0.048 0.283 0.669 0.9856
2 21895 p182444 3465aaf82da834c0582ebd0ef8040ca0 Ms. AZ 2016-08-31 12:03:56 Grades 6-8 Soccer Equipment for AWESOME Middle School Stu... \r\n\"True champions aren't always the ones th... The students on the campus come to school know... ... Health_Wellness TeamSports \r\n\"True champions aren't always the ones th... true champions not always ones win guts by mia... 202 soccer equipment awesome middle school students 6 0.122 0.219 0.659 0.9816

3 rows × 26 columns

1.4.1 Project_grade preprocessing

In [26]:
project_data['project_grade_category'] = project_data['project_grade_category'].str.replace(" ", "_")
project_data['project_grade_category'].value_counts()
Out[26]:
Grades_PreK-2    14199
Grades_3-5       11888
Grades_6-8        5415
Grades_9-12       3498
Name: project_grade_category, dtype: int64

Preprocessing teacher_prefix

In [27]:
project_data['teacher_prefix'] = project_data['teacher_prefix'].str.replace(".","")
project_data['teacher_prefix'].value_counts()
Out[27]:
Mrs        18352
Ms         12530
Mr          3364
Teacher      752
Name: teacher_prefix, dtype: int64

1.5 Preparing data for models

In [28]:
project_data.columns
Out[28]:
Index(['Unnamed: 0', 'id', 'teacher_id', 'teacher_prefix', 'school_state',
       'project_submitted_datetime', 'project_grade_category', 'project_title',
       'project_essay_1', 'project_essay_2', 'project_essay_3',
       'project_essay_4', 'project_resource_summary',
       'teacher_number_of_previously_posted_projects', 'project_is_approved',
       'clean_categories', 'clean_subcategories', 'essay',
       'preprocessed_essays', 'proj_essay_wrd_count', 'preprocessed_titles',
       'proj_title_wrd_count', 'Essay_neg_ss', 'Essay_pos_ss', 'Essay_neu_ss',
       'Essay_compound_ss'],
      dtype='object')

we are going to consider

   - school_state : categorical data
   - clean_categories : categorical data
   - clean_subcategories : categorical data
   - project_grade_category : categorical data
   - teacher_prefix : categorical data

   - project_title : text data
   - text : text data
   - project_resource_summary: text data (optinal)

   - quantity : numerical (optinal)
   - teacher_number_of_previously_posted_projects : numerical
   - price : numerical

Split data into train,test and Cross validate

In [29]:
Y = project_data['project_is_approved'].values
project_data.drop(['project_is_approved'], axis=1, inplace=True)
In [30]:
X = project_data
X.head(1)
Out[30]:
Unnamed: 0 id teacher_id teacher_prefix school_state project_submitted_datetime project_grade_category project_title project_essay_1 project_essay_2 ... clean_subcategories essay preprocessed_essays proj_essay_wrd_count preprocessed_titles proj_title_wrd_count Essay_neg_ss Essay_pos_ss Essay_neu_ss Essay_compound_ss
0 160221 p253737 c90749f5d961ff158d4b4d1e7dc665fc Mrs IN 2016-12-05 13:43:57 Grades_PreK-2 Educational Support for English Learners at Home My students are English learners that are work... \"The limits of your language are the limits o... ... ESL Literacy My students are English learners that are work... my students english learners working english s... 161 educational support english learners home 5 0.012 0.144 0.844 0.9694

1 rows × 25 columns

In [31]:
# train test split
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, stratify=Y)
X_train, X_cv, Y_train, Y_cv = train_test_split(X_train, Y_train, test_size=0.33, stratify=Y_train)

1.5.1 Vectorizing Categorical data

One Hot Encode - Clean_Categories

In [32]:
# we use count vectorizer to convert the values into one hot encoded features

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)

from sklearn.feature_extraction.text import CountVectorizer
vectorizer_categories = CountVectorizer(vocabulary=list(sorted_cat_dict.keys()), lowercase=False, binary=True)
vectorizer_categories.fit(X_train['clean_categories'].values)


categories_one_hot_train = vectorizer_categories.fit_transform(X_train['clean_categories'].values)
categories_one_hot_test = vectorizer_categories.transform(X_test['clean_categories'].values)
categories_one_hot_cv = vectorizer_categories.transform(X_cv['clean_categories'].values)

print("After vectorizations")

print("Shape of Train data - one hot encoding ",categories_one_hot_train.shape)
print("Shape of Test data - one hot encoding ",categories_one_hot_test.shape)
print("Shape of CV data - one hot encoding ",categories_one_hot_cv.shape)
print("="*100)
print(vectorizer_categories.get_feature_names())
print("="*100)
(15711, 25) (15711,)
(11550, 25) (11550,)
(7739, 25) (7739,)
====================================================================================================
After vectorizations
Shape of Train data - one hot encoding  (15711, 9)
Shape of Test data - one hot encoding  (11550, 9)
Shape of CV data - one hot encoding  (7739, 9)
====================================================================================================
['Warmth', 'Care_Hunger', 'History_Civics', 'Music_Arts', 'AppliedLearning', 'SpecialNeeds', 'Health_Sports', 'Math_Science', 'Literacy_Language']
====================================================================================================

One Hot Encode - Clean_Sub-Categories

In [33]:
# we use count vectorizer to convert the values into one 
print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)


vectorizer_sub_cat = CountVectorizer(vocabulary=list(sorted_sub_cat_dict.keys()), lowercase=False, binary=True)
vectorizer_sub_cat.fit(X_train['clean_subcategories'].values)

sub_cat_one_hot_train = vectorizer_sub_cat.fit_transform(X_train['clean_subcategories'].values)
sub_cat_one_hot_test = vectorizer_sub_cat.transform(X_test['clean_subcategories'].values)
sub_cat_one_hot_cv = vectorizer_sub_cat.transform(X_cv['clean_subcategories'].values)

print("After vectorizations")

print("Shape of Train data - one hot encoding ",sub_cat_one_hot_train.shape)
print("Shape of Test data - one hot encoding",sub_cat_one_hot_test.shape)
print("Shape of CV data - one hot encoding",sub_cat_one_hot_cv.shape)
print("="*100)

print(vectorizer_sub_cat.get_feature_names())
print("="*100)
(15711, 25) (15711,)
(11550, 25) (11550,)
(7739, 25) (7739,)
====================================================================================================
After vectorizations
Shape of Train data - one hot encoding  (15711, 30)
Shape of Test data - one hot encoding (11550, 30)
Shape of CV data - one hot encoding (7739, 30)
====================================================================================================
['Economics', 'CommunityService', 'FinancialLiteracy', 'ParentInvolvement', 'Extracurricular', 'Civics_Government', 'ForeignLanguages', 'NutritionEducation', 'Warmth', 'Care_Hunger', 'SocialSciences', 'PerformingArts', 'CharacterEducation', 'TeamSports', 'Other', 'College_CareerPrep', 'Music', 'History_Geography', 'Health_LifeScience', 'EarlyDevelopment', 'ESL', 'Gym_Fitness', 'EnvironmentalScience', 'VisualArts', 'Health_Wellness', 'AppliedSciences', 'SpecialNeeds', 'Literature_Writing', 'Mathematics', 'Literacy']
====================================================================================================
In [34]:
# you can do the similar thing with state, teacher_prefix and project_grade_category also

One Hot Encode - School_States

In [35]:
my_counter = Counter()
for state in project_data['school_state'].values:
    my_counter.update(state.split())
In [36]:
school_state_cat_dict = dict(my_counter)
sorted_school_state_cat_dict = dict(sorted(school_state_cat_dict.items(), key=lambda kv: kv[1]))
In [37]:
## we use count vectorizer to convert the values into one hot encoded features

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)

vectorizer_school_state = CountVectorizer(vocabulary=list(sorted_school_state_cat_dict.keys()), lowercase=False, binary=True)
vectorizer_school_state.fit(X_train['school_state'].values)

school_state_one_hot_train = vectorizer_school_state.fit_transform(X_train['school_state'].values)
school_state_one_hot_test = vectorizer_school_state.transform(X_test['school_state'].values)
school_state_one_hot_cv = vectorizer_school_state.transform(X_cv['school_state'].values)

print("After vectorizations")


print("Shape of Train data - one hot encoding",school_state_one_hot_train.shape)
print("Shape of Test data - one hot encoding",school_state_one_hot_test.shape)
print("Shape of CV data - one hot encoding",school_state_one_hot_cv.shape)
print("="*100)
print(vectorizer_school_state.get_feature_names())
print("="*100)
(15711, 25) (15711,)
(11550, 25) (11550,)
(7739, 25) (7739,)
====================================================================================================
After vectorizations
Shape of Train data - one hot encoding (15711, 51)
Shape of Test data - one hot encoding (11550, 51)
Shape of CV data - one hot encoding (7739, 51)
====================================================================================================
['VT', 'WY', 'ND', 'MT', 'RI', 'NH', 'SD', 'DE', 'AK', 'NE', 'ME', 'HI', 'WV', 'NM', 'DC', 'ID', 'IA', 'KS', 'AR', 'CO', 'MN', 'MS', 'OR', 'KY', 'MD', 'NV', 'AL', 'UT', 'CT', 'TN', 'WI', 'VA', 'NJ', 'AZ', 'OK', 'MA', 'LA', 'WA', 'MO', 'IN', 'OH', 'PA', 'MI', 'GA', 'SC', 'IL', 'NC', 'FL', 'TX', 'NY', 'CA']
====================================================================================================

One Hot Encode - Project_Grade_Category

In [38]:
my_counter = Counter()
for project_grade in project_data['project_grade_category'].values:
    my_counter.update(project_grade.split())
In [39]:
project_grade_cat_dict = dict(my_counter)
sorted_project_grade_cat_dict = dict(sorted(project_grade_cat_dict.items(), key=lambda kv: kv[1]))
In [40]:
## we use count vectorizer to convert the values into one hot encoded features

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)

vectorizer_project_grade_cat = CountVectorizer(vocabulary=list(sorted_project_grade_cat_dict.keys()), lowercase=False, binary=True)
vectorizer_project_grade_cat.fit(X_train['project_grade_category'].values)

project_grade_cat_one_hot_train = vectorizer_project_grade_cat.fit_transform(X_train['project_grade_category'].values)
project_grade_cat_one_hot_test = vectorizer_project_grade_cat.transform(X_test['project_grade_category'].values)
project_grade_cat_one_hot_cv = vectorizer_project_grade_cat.transform(X_cv['project_grade_category'].values)

print("After vectorizations")
print("="*100)
print("Shape of Train data - one hot encoding",project_grade_cat_one_hot_train.shape)
print("Shape of Test data - one hot encoding",project_grade_cat_one_hot_test.shape)
print("Shape of CV data - one hot encoding",project_grade_cat_one_hot_cv.shape)
print("="*100)
print(vectorizer_project_grade_cat.get_feature_names())
(15711, 25) (15711,)
(11550, 25) (11550,)
(7739, 25) (7739,)
====================================================================================================
After vectorizations
====================================================================================================
Shape of Train data - one hot encoding (15711, 4)
Shape of Test data - one hot encoding (11550, 4)
Shape of CV data - one hot encoding (7739, 4)
====================================================================================================
['Grades_9-12', 'Grades_6-8', 'Grades_3-5', 'Grades_PreK-2']

One Hot Encode - Teacher_Prefix

In [41]:
my_counter = Counter()
for teacher_prefix in project_data['teacher_prefix'].values:
    teacher_prefix = str(teacher_prefix)
    my_counter.update(teacher_prefix.split())
In [42]:
teacher_prefix_cat_dict = dict(my_counter)
sorted_teacher_prefix_cat_dict = dict(sorted(teacher_prefix_cat_dict.items(), key=lambda kv: kv[1]))
In [43]:
vectorizer_teacher_prefix_cat = CountVectorizer(vocabulary=list(sorted_teacher_prefix_cat_dict.keys()), lowercase=False, binary=True)
vectorizer_teacher_prefix_cat.fit(X_train['teacher_prefix'].values.astype("U"))

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)

teacher_prefix_cat_one_hot_train = vectorizer_teacher_prefix_cat.fit_transform(X_train['teacher_prefix'].values.astype("U"))
teacher_prefix_cat_one_hot_test = vectorizer_teacher_prefix_cat.transform(X_test['teacher_prefix'].values.astype("U"))
teacher_prefix_cat_one_hot_cv = vectorizer_teacher_prefix_cat.transform(X_cv['teacher_prefix'].values.astype("U"))
print("After vectorizations")
print("="*100)

print("Shape of Train data - one hot encoding",teacher_prefix_cat_one_hot_train.shape)
print("Shape of Test data - one hot encoding ",teacher_prefix_cat_one_hot_test.shape)
print("Shape of CV data - one hot encoding ",teacher_prefix_cat_one_hot_cv.shape)
print("="*100)


print(vectorizer_teacher_prefix_cat.get_feature_names())
(15711, 25) (15711,)
(11550, 25) (11550,)
(7739, 25) (7739,)
====================================================================================================
After vectorizations
====================================================================================================
Shape of Train data - one hot encoding (15711, 5)
Shape of Test data - one hot encoding  (11550, 5)
Shape of CV data - one hot encoding  (7739, 5)
====================================================================================================
['nan', 'Teacher', 'Mr', 'Ms', 'Mrs']

1.5.2 Vectorizing Text data

1.5.2.1 Bag of words

BOW of eassys - Train/Test/CV Data

In [44]:
# We are considering only the words which appeared in at least 10 documents(rows or projects).
vectorizer_essay_bow = CountVectorizer(ngram_range=(2, 2),min_df=10,max_features=5000)
vectorizer_essay_bow.fit(X_train['preprocessed_essays'])

# BOW for essays Train Data
essay_bow_train = vectorizer_essay_bow.fit_transform(X_train['preprocessed_essays'])
print("Shape of matrix for TRAIN data ",essay_bow_train.shape)

# BOW for essays Test Data
essay_bow_test = vectorizer_essay_bow.transform(X_test['preprocessed_essays'])
print("Shape of matrix for TEST data",essay_bow_test.shape)

# BOW for essays CV Data
essay_bow_cv = vectorizer_essay_bow.transform(X_cv['preprocessed_essays'])
print("Shape of matrix for CV data ",essay_bow_cv.shape)
Shape of matrix for TRAIN data  (15711, 5000)
Shape of matrix for TEST data (11550, 5000)
Shape of matrix for CV data  (7739, 5000)

BOW of Project Titles - Train/Test/CV Data

In [45]:
vectorizer_title_bow = CountVectorizer(ngram_range=(2, 2),min_df=10,max_features=5000)
vectorizer_title_bow.fit(X_train['preprocessed_titles'])

# BOW for title Train Data
title_bow_train = vectorizer_title_bow.fit_transform(X_train['preprocessed_titles'])
print("Shape of matrix for TRAIN data ",title_bow_train.shape)

# BOW for title Test Data
title_bow_test = vectorizer_title_bow.transform(X_test['preprocessed_titles'])
print("Shape of matrix for TEST data",title_bow_test.shape)

# BOW for title CV Data
title_bow_cv = vectorizer_title_bow.transform(X_cv['preprocessed_titles'])
print("Shape of matrix for CV data ",title_bow_cv.shape)
Shape of matrix for TRAIN data  (15711, 410)
Shape of matrix for TEST data (11550, 410)
Shape of matrix for CV data  (7739, 410)

1.5.2.2 TFIDF vectorizer for essay

In [46]:
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer_essay_tfidf = TfidfVectorizer(ngram_range=(2, 2),min_df=10,max_features=5000)
vectorizer_essay_tfidf.fit(X_train['preprocessed_essays'])

#tidf Train Data
essay_tfidf_train = vectorizer_essay_tfidf.fit_transform(X_train['preprocessed_essays'])
print("Shape of matrix for TRAIN data",essay_tfidf_train.shape)

#tidf Test Data
essay_tfidf_test = vectorizer_essay_tfidf.transform(X_test['preprocessed_essays'])
print("Shape of matrix for TEST data",essay_tfidf_test.shape)

#tidf CV Data
essay_tfidf_cv = vectorizer_essay_tfidf.transform(X_cv['preprocessed_essays'])
print("Shape of matrix for CV data",essay_tfidf_cv.shape)
Shape of matrix for TRAIN data (15711, 5000)
Shape of matrix for TEST data (11550, 5000)
Shape of matrix for CV data (7739, 5000)

TFIDF vectorizer for Title

In [47]:
vectorizer_title_tfidf = TfidfVectorizer(ngram_range=(2, 2),min_df=10,max_features=5000)
vectorizer_title_tfidf.fit(X_train['preprocessed_titles'])

#tidf Train Data
title_tfidf_train = vectorizer_title_tfidf.fit_transform(X_train['preprocessed_titles'])
print("Shape of matrix for TRAIN data",title_tfidf_train.shape)

#tidf Test Data
title_tfidf_test = vectorizer_title_tfidf.transform(X_test['preprocessed_titles'])
print("Shape of matrix for TEST data",title_tfidf_test.shape)

#tidf CV Data
title_tfidf_cv = vectorizer_title_tfidf.transform(X_cv['preprocessed_titles'])
print("Shape of matrix for CV data",title_tfidf_cv.shape)
Shape of matrix for TRAIN data (15711, 410)
Shape of matrix for TEST data (11550, 410)
Shape of matrix for CV data (7739, 410)

1.5.2.3 Using Pretrained Models: Avg W2V

In [48]:
# stronging variables into pickle files python: http://www.jessicayung.com/how-to-use-pickle-to-save-and-load-variables-in-python/
# make sure you have the glove_vectors file
with open('glove_vectors', 'rb') as f:
    model = pickle.load(f)
    glove_words =  set(model.keys())
In [49]:
# average Word2Vec Function
# compute average word2vec for each review.
# the avg-w2v for each sentence/review is stored in this list
def avg_w2v_vectors_func(sentance):
    vector = np.zeros(300) # as word vectors are of zero length
    cnt_words =0; # num of words with a valid vector in the sentence/review
    for word in sentence.split(): # for each word in a review/sentence
        if word in glove_words:
            vector += model[word]
            cnt_words += 1
    if cnt_words != 0:
        vector /= cnt_words
    return vector

Train/Test/CV Data - Avg-W2V for essay

In [50]:
essay_avg_w2v_train = []
essay_avg_w2v_test  = []
essay_avg_w2v_cv    = []

for sentence in tqdm(X_train['preprocessed_essays']):
    essay_avg_w2v_train.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Train data
    
# Avg-w2v for Train data    
print("len(essay_avg_w2v_train):",len(essay_avg_w2v_train))
print("len(essay_avg_w2v_train[0])",len(essay_avg_w2v_train[0]))

for sentence in tqdm(X_test['preprocessed_essays']):
    essay_avg_w2v_test.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Test data

# Avg-w2v for Test data
print("len(essay_avg_w2v_test):",len(essay_avg_w2v_test))
print("len(essay_avg_w2v_test[0])",len(essay_avg_w2v_test[0]))


for sentence in tqdm(X_cv['preprocessed_essays']):    
    essay_avg_w2v_cv.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for CV data

# Avg-w2v for CV data
print("len(essay_avg_w2v_cv):",len(essay_avg_w2v_cv))
print("len(essay_avg_w2v_cv[0])",len(essay_avg_w2v_cv[0]))
100%|██████████████████████████████████████████████████████████████████████████| 15711/15711 [00:06<00:00, 2341.31it/s]
len(essay_avg_w2v_train): 15711
len(essay_avg_w2v_train[0]) 300
100%|██████████████████████████████████████████████████████████████████████████| 11550/11550 [00:04<00:00, 2331.66it/s]
len(essay_avg_w2v_test): 11550
len(essay_avg_w2v_test[0]) 300
100%|████████████████████████████████████████████████████████████████████████████| 7739/7739 [00:03<00:00, 2302.13it/s]
len(essay_avg_w2v_cv): 7739
len(essay_avg_w2v_cv[0]) 300
In [51]:
title_avg_w2v_train = []
title_avg_w2v_test  = []

for sentence in tqdm(X_train['preprocessed_titles']):
    title_avg_w2v_train.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Train data
    
# Avg-w2v for Train data    
print("len(title_avg_w2v_train):",len(title_avg_w2v_train))
print("len(title_avg_w2v_train[0])",len(title_avg_w2v_train[0]))

for sentence in tqdm(X_test['preprocessed_titles']):
    title_avg_w2v_test.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Test data

# Avg-w2v for Test data
print("len(title_avg_w2v_test):",len(title_avg_w2v_test))
print("len(title_avg_w2v_test[0])",len(title_avg_w2v_test[0]))
100%|█████████████████████████████████████████████████████████████████████████| 15711/15711 [00:00<00:00, 38009.03it/s]
len(title_avg_w2v_train): 15711
len(title_avg_w2v_train[0]) 300
100%|█████████████████████████████████████████████████████████████████████████| 11550/11550 [00:00<00:00, 38262.64it/s]
len(title_avg_w2v_test): 11550
len(title_avg_w2v_test[0]) 300

1.5.2.3 Using Pretrained Models: TFIDF weighted W2V

In [52]:
# S = ["abc def pqr", "def def def abc", "pqr pqr def"]
tfidf_model = TfidfVectorizer()
tfidf_model.fit(X_train['preprocessed_essays'])
# we are converting a dictionary with word as a key, and the idf as a value
dictionary = dict(zip(tfidf_model.get_feature_names(), list(tfidf_model.idf_)))
tfidf_words = set(tfidf_model.get_feature_names())
In [53]:
# Compute  TFIDF weighted W2V for each sentence of the review.

def tf_idf_weight_func(sentence): # for each review/sentence
    vector = np.zeros(300) # as word vectors are of zero length
    tf_idf_weight =0; # num of words with a valid vector in the sentence/review
    for word in sentence.split(): # for each word in a review/sentence
        if (word in glove_words) and (word in tfidf_words):
            vec = model[word] # getting the vector for each word
            # here we are multiplying idf value(dictionary[word]) and the tf value((sentence.count(word)/len(sentence.split())))
            tf_idf = dictionary[word]*(sentence.count(word)/len(sentence.split())) # getting the tfidf value for each word
            vector += (vec * tf_idf) # calculating tfidf weighted w2v
            tf_idf_weight += tf_idf
    if tf_idf_weight != 0:
        vector /= tf_idf_weight
    return vector

Train/Test/CV Data - TFIDF weighted W2V for essay

In [54]:
essay_tfidf_w2v_train = []
essay_tfidf_w2v_test  = []
essay_tfidf_w2v_cv    = []

for sentence in tqdm(X_train['preprocessed_essays']):
    essay_tfidf_w2v_train.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for Train data
print("len(essay_tfidf_w2v_train)",len(essay_tfidf_w2v_train))
print("len(essay_tfidf_w2v_train[0])",len(essay_tfidf_w2v_train[0]))

for sentence in tqdm(X_test['preprocessed_essays']):
    essay_tfidf_w2v_test.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for Test data
print("len(essay_tfidf_w2v_test)",len(essay_tfidf_w2v_test))
print("len(essay_tfidf_w2v_test[0])",len(essay_tfidf_w2v_test[0]))

for sentence in tqdm(X_cv['preprocessed_essays']):
    essay_tfidf_w2v_cv.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for CV data
print("len(essay_tfidf_w2v_cv)",len(essay_tfidf_w2v_cv))
print("len(essay_tfidf_w2v_cv[0])",len(essay_tfidf_w2v_cv[0]))
100%|█████████████████████████████████████████████████████████████████████████| 15711/15711 [00:00<00:00, 28509.19it/s]
len(essay_tfidf_w2v_train) 15711
len(essay_tfidf_w2v_train[0]) 300
100%|█████████████████████████████████████████████████████████████████████████| 11550/11550 [00:00<00:00, 26319.72it/s]
len(essay_tfidf_w2v_test) 11550
len(essay_tfidf_w2v_test[0]) 300
100%|███████████████████████████████████████████████████████████████████████████| 7739/7739 [00:00<00:00, 19703.43it/s]
len(essay_tfidf_w2v_cv) 7739
len(essay_tfidf_w2v_cv[0]) 300

Train/Test/CV Data - Avg-W2V for essay

In [55]:
title_avg_w2v_train = []
title_avg_w2v_test  = []
title_avg_w2v_cv    = []

for sentence in tqdm(X_train['preprocessed_titles']):
    title_avg_w2v_train.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Train data
    
# Avg-w2v for Train data    
print("len(title_avg_w2v_train):",len(title_avg_w2v_train))
print("len(title_avg_w2v_train[0])",len(title_avg_w2v_train[0]))

for sentence in tqdm(X_test['preprocessed_titles']):
    title_avg_w2v_test.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for Test data

# Avg-w2v for Test data
print("len(title_avg_w2v_test):",len(title_avg_w2v_test))
print("len(title_avg_w2v_test[0])",len(title_avg_w2v_test[0]))


for sentence in tqdm(X_cv['preprocessed_titles']):    
    title_avg_w2v_cv.append(avg_w2v_vectors_func(sentance)) # Avg-w2v for CV data

# Avg-w2v for CV data
print("len(title_avg_w2v_cv):",len(title_avg_w2v_cv))
print("len(title_avg_w2v_cv[0])",len(title_avg_w2v_cv[0]))
100%|█████████████████████████████████████████████████████████████████████████| 15711/15711 [00:00<00:00, 39670.17it/s]
len(title_avg_w2v_train): 15711
len(title_avg_w2v_train[0]) 300
100%|█████████████████████████████████████████████████████████████████████████| 11550/11550 [00:00<00:00, 34191.22it/s]
len(title_avg_w2v_test): 11550
len(title_avg_w2v_test[0]) 300
100%|███████████████████████████████████████████████████████████████████████████| 7739/7739 [00:00<00:00, 25725.83it/s]
len(title_avg_w2v_cv): 7739
len(title_avg_w2v_cv[0]) 300

Train/Test/CV Data - TFIDF weighted W2V for Project Titles

In [56]:
title_tfidf_w2v_train  = []
title_tfidf_w2v_test  = []
title_tfidf_w2v_cv    = []

for sentence in tqdm(X_train['preprocessed_titles']):
    title_tfidf_w2v_train.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for Train data
print("len(title_tfidf_w2v_train)",len(title_tfidf_w2v_train))
print("len(title_tfidf_w2v_train[0])",len(title_tfidf_w2v_train[0]))

for sentence in tqdm(X_test['preprocessed_titles']):
    title_tfidf_w2v_test.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for Test data
print("len(title_tfidf_w2v_test)",len(title_tfidf_w2v_test))
print("len(title_tfidf_w2v_test[0])",len(title_tfidf_w2v_test[0]))

for sentence in tqdm(X_cv['preprocessed_titles']):
    title_tfidf_w2v_cv.append(tf_idf_weight_func(sentance)) #  TFIDF weighted W2V for CV data
print("len(title_tfidf_w2v_cv)",len(title_tfidf_w2v_cv))
print("len(title_tfidf_w2v_cv[0])",len(title_tfidf_w2v_cv[0]))
100%|█████████████████████████████████████████████████████████████████████████| 15711/15711 [00:00<00:00, 28124.50it/s]
len(title_tfidf_w2v_train) 15711
len(title_tfidf_w2v_train[0]) 300
100%|█████████████████████████████████████████████████████████████████████████| 11550/11550 [00:00<00:00, 28726.15it/s]
len(title_tfidf_w2v_test) 11550
len(title_tfidf_w2v_test[0]) 300
100%|███████████████████████████████████████████████████████████████████████████| 7739/7739 [00:00<00:00, 27200.46it/s]
len(title_tfidf_w2v_cv) 7739
len(title_tfidf_w2v_cv[0]) 300

1.5.3 Vectorizing Numerical features

In [57]:
price_data = resource_data.groupby('id').agg({'price':'sum', 'quantity':'sum'}).reset_index()
X_train = pd.merge(X_train, price_data, on='id', how='left')
X_test = pd.merge(X_test, price_data, on='id', how='left')
X_cv = pd.merge(X_cv, price_data, on='id', how='left')
In [58]:
from sklearn.preprocessing import Normalizer

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)
normalizer = Normalizer()

# normalizer.fit(X_train['price'].values)
# this will rise an error Expected 2D array, got 1D array instead: 
# array=[105.22 215.96  96.01 ... 368.98  80.53 709.67].
# Reshape your data either using 
# array.reshape(-1, 1) if your data has a single feature 
# array.reshape(1, -1)  if it contains a single sample.

normalizer.fit(X_train['price'].values.reshape(-1,1))

price_data_train = normalizer.fit_transform(X_train['price'].values.reshape(-1,1))

price_data_test = normalizer.transform(X_test['price'].values.reshape(-1,1))

price_data_cv = normalizer.transform(X_cv['price'].values.reshape(-1,1))

print("After vectorizations")
print("="*100)
print(price_data_train.shape, Y_train.shape)
print(price_data_test.shape, Y_test.shape)
print(price_data_cv.shape, Y_cv.shape)
print("="*100)
(15711, 27) (15711,)
(11550, 27) (11550,)
(7739, 27) (7739,)
====================================================================================================
After vectorizations
====================================================================================================
(15711, 1) (15711,)
(11550, 1) (11550,)
(7739, 1) (7739,)
====================================================================================================

Vectorizing - Quantity Feature

In [59]:
normalizer = Normalizer()

# normalizer.fit(X_train['price'].values)
# this will rise an error Expected 2D array, got 1D array instead: 
# array=[105.22 215.96  96.01 ... 368.98  80.53 709.67].
# Reshape your data either using 
# array.reshape(-1, 1) if your data has a single feature 
# array.reshape(1, -1)  if it contains a single sample.

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)
normalizer.fit(X_train['quantity'].values.reshape(-1,1))

quant_train = normalizer.fit_transform(X_train['quantity'].values.reshape(-1,1))
quant_cv = normalizer.transform(X_cv['quantity'].values.reshape(-1,1))
quant_test = normalizer.transform(X_test['quantity'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(quant_train.shape, Y_train.shape)
print(quant_cv.shape, Y_cv.shape)
print(quant_test.shape, Y_test.shape)
print("="*100)
(15711, 27) (15711,)
(11550, 27) (11550,)
(7739, 27) (7739,)
====================================================================================================
====================================================================================================
After vectorizations
(15711, 1) (15711,)
(7739, 1) (7739,)
(11550, 1) (11550,)
====================================================================================================

Vectorizing - teacher_number_of_previously_posted_projects

In [60]:
normalizer = Normalizer()

# normalizer.fit(X_train['price'].values)
# this will rise an error Expected 2D array, got 1D array instead: 
# array=[105.22 215.96  96.01 ... 368.98  80.53 709.67].
# Reshape your data either using 
# array.reshape(-1, 1) if your data has a single feature 
# array.reshape(1, -1)  if it contains a single sample.

print(X_train.shape, Y_train.shape)
print(X_test.shape, Y_test.shape)
print(X_cv.shape, Y_cv.shape)

print("="*100)
normalizer.fit(X_train['teacher_number_of_previously_posted_projects'].values.reshape(-1,1))

prev_no_projects_train = normalizer.fit_transform(X_train['teacher_number_of_previously_posted_projects'].values.reshape(-1,1))
prev_no_projects_cv = normalizer.transform(X_cv['teacher_number_of_previously_posted_projects'].values.reshape(-1,1))
prev_no_projects_test = normalizer.transform(X_test['teacher_number_of_previously_posted_projects'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(prev_no_projects_train.shape, Y_train.shape)
print(prev_no_projects_cv.shape, Y_cv.shape)
print(prev_no_projects_test.shape, Y_test.shape)
print("="*100)
(15711, 27) (15711,)
(11550, 27) (11550,)
(7739, 27) (7739,)
====================================================================================================
====================================================================================================
After vectorizations
(15711, 1) (15711,)
(7739, 1) (7739,)
(11550, 1) (11550,)
====================================================================================================

Vectorizing - Word count title

In [61]:
normalizer = Normalizer()

normalizer.fit(X_train['proj_title_wrd_count'].values.reshape(-1,1))

title_cnt_train = normalizer.fit_transform(X_train['proj_title_wrd_count'].values.reshape(-1,1))
title_cnt_test = normalizer.transform(X_test['proj_title_wrd_count'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(title_cnt_train.shape, Y_train.shape)
print(title_cnt_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(15711, 1) (15711,)
(11550, 1) (11550,)
====================================================================================================

Vectorizing - Essay count title

In [62]:
normalizer = Normalizer()

normalizer.fit(X_train['proj_essay_wrd_count'].values.reshape(-1,1))

essay_cnt_train = normalizer.fit_transform(X_train['proj_essay_wrd_count'].values.reshape(-1,1))
essay_cnt_test = normalizer.transform(X_test['proj_essay_wrd_count'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(title_cnt_train.shape, Y_train.shape)
print(title_cnt_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(15711, 1) (15711,)
(11550, 1) (11550,)
====================================================================================================

Vectorizing - Sentiment Score negative

In [63]:
normalizer = Normalizer()

normalizer.fit(X_train['Essay_neg_ss'].values.reshape(-1,1))

essay_neg_train = normalizer.fit_transform(X_train['Essay_neg_ss'].values.reshape(-1,1))
essay_neg_test = normalizer.transform(X_test['Essay_neg_ss'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(essay_neg_train.shape, Y_train.shape)
print(essay_neg_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(15711, 1) (15711,)
(11550, 1) (11550,)
====================================================================================================

Vectorizing - Sentiment Score positive

In [64]:
normalizer = Normalizer()

normalizer.fit(X_train['Essay_pos_ss'].values.reshape(-1,1))

essay_pos_train = normalizer.fit_transform(X_train['Essay_pos_ss'].values.reshape(-1,1))
essay_pos_test = normalizer.transform(X_test['Essay_pos_ss'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(essay_pos_train.shape, Y_train.shape)
print(essay_pos_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(15711, 1) (15711,)
(11550, 1) (11550,)
====================================================================================================

Vectorizing - Sentiment Score neutral

In [65]:
normalizer = Normalizer()

normalizer.fit(X_train['Essay_neu_ss'].values.reshape(-1,1))

essay_neu_train = normalizer.fit_transform(X_train['Essay_neu_ss'].values.reshape(-1,1))
essay_neu_test = normalizer.transform(X_test['Essay_neu_ss'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(essay_neu_train.shape, Y_train.shape)
print(essay_neu_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(15711, 1) (15711,)
(11550, 1) (11550,)
====================================================================================================

Vectorizing - Sentiment Score compound

In [66]:
normalizer = Normalizer()

normalizer.fit(X_train['Essay_compound_ss'].values.reshape(-1,1))

essay_compound_train = normalizer.fit_transform(X_train['Essay_compound_ss'].values.reshape(-1,1))
essay_compund_test = normalizer.transform(X_test['Essay_compound_ss'].values.reshape(-1,1))

print("="*100)
print("After vectorizations")
print(essay_compound_train.shape, Y_train.shape)
print(essay_compund_test.shape, Y_test.shape)
print("="*100)
====================================================================================================
After vectorizations
(15711, 1) (15711,)
(11550, 1) (11550,)
====================================================================================================

Assignment 7: SVM

  1. [Task-1] Apply Support Vector Machines(SGDClassifier with hinge loss: Linear SVM) on these feature sets
    • Set 1: categorical, numerical features + project_title(BOW) + preprocessed_eassay (BOW)
    • Set 2: categorical, numerical features + project_title(TFIDF)+ preprocessed_eassay (TFIDF)
    • Set 3: categorical, numerical features + project_title(AVG W2V)+ preprocessed_eassay (AVG W2V)
    • Set 4: categorical, numerical features + project_title(TFIDF W2V)+ preprocessed_eassay (TFIDF W2V)

  2. The hyper paramter tuning (best alpha in range [10^-4 to 10^4], and the best penalty among 'l1', 'l2')
    • Find the best hyper parameter which will give the maximum AUC value
    • Find the best hyper paramter using k-fold cross validation or simple cross validation data
    • Use gridsearch cv or randomsearch cv or you can also write your own for loops to do this task of hyperparameter tuning

  3. Representation of results
    • You need to plot the performance of model both on train data and cross validation data for each hyper parameter, like shown in the figure.
    • Once after you found the best hyper parameter, you need to train your model with it, and find the AUC on test data and plot the ROC curve on both train and test.
    • Along with plotting ROC curve, you need to print the confusion matrix with predicted and original labels of test data points. Please visualize your confusion matrices using seaborn heatmaps.

  4. [Task-2] Apply the Support Vector Machines on these features by finding the best hyper paramter as suggested in step 2 and step 3

Note: Data Leakage

  1. There will be an issue of data-leakage if you vectorize the entire data and then split it into train/cv/test.
  2. To avoid the issue of data-leakage, make sure to split your data first and then vectorize it.
  3. While vectorizing your data, apply the method fit_transform() on you train data, and apply the method transform() on cv/test data.
  4. For more details please go through this link.

2. Support Vector Machines

SET 1

Applying Support Vector Machines on BOW

In [167]:
# please write all the code with proper documentation, and proper titles for each subsection
# go through documentations and blogs before you start coding
# first figure out what to do, and then think about how to do.
# reading and understanding error messages will be very much helpfull in debugging your code
# when you plot any graph make sure you use 
    # a. Title, that describes your plot, this will be very helpful to the reader
    # b. Legends if needed
    # c. X-axis label
    # d. Y-axis label
    
In [168]:
from scipy.sparse import hstack

X_train_merge = hstack((categories_one_hot_train, sub_cat_one_hot_train, school_state_one_hot_train, project_grade_cat_one_hot_train, teacher_prefix_cat_one_hot_train, price_data_train, quant_train, prev_no_projects_train,title_bow_train, essay_bow_train)).tocsr()
X_test_merge = hstack((categories_one_hot_test, sub_cat_one_hot_test, school_state_one_hot_test, project_grade_cat_one_hot_test, teacher_prefix_cat_one_hot_test, price_data_test, quant_test, prev_no_projects_test,title_bow_test, essay_bow_test)).tocsr()

Best hyper prameter using the ROC/AUC higest value and K-fold cross validation

In [169]:
def batch_predict(clf, data):
    # roc_auc_score(y_true, y_score) the 2nd parameter should be probability estimates of the positive class
    # not the predicted outputs

    y_data_pred = []
    tr_loop = data.shape[0] - data.shape[0]%1000
    # consider you X_tr shape is 49041, then your cr_loop will be 49041 - 49041%1000 = 49000
    # in this for loop we will iterate unti the last 1000 multiplier
    for i in range(0, tr_loop, 1000):
        y_data_pred.extend(clf.predict_proba(data[i:i+1000])[:,1])
    # we will be predicting for the last data points
    y_data_pred.extend(clf.predict_proba(data[tr_loop:])[:,1])
    
    return y_data_pred
In [170]:
#https://www.geeksforgeeks.org/ml-hyperparameter-tuning/

# ValueError: alpha must be >= 0, To resolve this error used values from 10^1 to 10^8


svm = SGDClassifier(class_weight='balanced')
parameters = {'loss' :['hinge'],'penalty' :["l1", "l2"],'alpha':[abs(math.log10(10**1)),abs(math.log10(10**2)),abs(math.log10(10**3)),abs(math.log10(10**4))
                       ,abs(math.log10(10**5)),abs(math.log10(10**6)),abs(math.log10(10**7))
                       ,abs(math.log10(10**8))]}

clf = GridSearchCV(svm, parameters, cv= 10, scoring='roc_auc')
grid_result = clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']

print('Best Score: ', grid_result.best_score_)
print('Best Params: ', grid_result.best_params_)
Best Score:  0.6034198169603189
Best Params:  {'alpha': 1.0, 'loss': 'hinge', 'penalty': 'l2'}

Plot the hyperparameter vs AUC curve using the best parms and best regularisation

In [171]:
svm = SGDClassifier(class_weight='balanced')

parameters = {'loss' :['hinge'],'penalty' :['l2'],'alpha':[abs(math.log10(10**1)),abs(math.log10(10**2)),abs(math.log10(10**3)),abs(math.log10(10**4))
                       ,abs(math.log10(10**5)),abs(math.log10(10**6)),abs(math.log10(10**7))
                       ,abs(math.log10(10**8))]}

clf = GridSearchCV(svm, parameters, cv= 10, scoring='roc_auc')

clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']

plt.figure(figsize=(20,10))

plt.plot(parameters['alpha'], train_auc, label='Train AUC')
plt.gca().fill_between(parameters['alpha'],train_auc - train_auc_std,train_auc + train_auc_std,alpha=0.3,color='darkblue')

plt.plot(parameters['alpha'], cv_auc, label='CV AUC')
plt.gca().fill_between(parameters['alpha'],cv_auc - cv_auc_std,cv_auc + cv_auc_std,alpha=0.3,color='darkorange')

plt.scatter(parameters['alpha'], train_auc, label='Train AUC points')
plt.scatter(parameters['alpha'], cv_auc, label='CV AUC points')


plt.legend()
plt.xlabel("Alpha: hyperparameter")
plt.ylabel("AUC")
plt.title("Alpha: hyperparameter v/s AUC plot")
plt.grid()
plt.show()
In [172]:
best_alpha =  10

#log of 10^1  =  1
#log of 10^2  =  2
#log of 10^3  =  3
#log of 10^4  =  4
#log of 10^5  =  5
#log of 10^6  =  6
#log of 10^7  =  7
#log of 10^8  =  8

Best Train Model using best Hyper parameter.

In [173]:
from sklearn.metrics import roc_curve, auc
from sklearn import linear_model
from sklearn.linear_model import SGDClassifier

svm = SGDClassifier(loss='hinge', penalty='l2',alpha = best_alpha,class_weight='balanced') #Multinominal Naive Bayes.
svm.fit(X_train_merge, Y_train)

y_train_pred = svm.decision_function(X_train_merge)    
y_test_pred = svm.decision_function(X_test_merge)

train_fpr, train_tpr, tr_thresholds = roc_curve(Y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(Y_test, y_test_pred)

plt.figure(figsize=(20,10))

plt.plot(train_fpr, train_tpr, label="Train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="Test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("True Positive Rate(TPR)")
plt.ylabel("False Positive Rate(FPR)")
plt.title("AUC")
plt.grid()
plt.show()

Confusion Matrix

In [174]:
def predict(proba, threshould, fpr, tpr):
    
    t = threshould[np.argmax(tpr*(1-fpr))]
    
    # (tpr*(1-fpr)) will be maximum if your fpr is very low and tpr is very high
    
    print("the maximum value of tpr*(1-fpr)", max(tpr*(1-fpr)), "for threshold", np.round(t,3))
    predictions = []
    for i in proba:
        if i>=t:
            predictions.append(1)
        else:
            predictions.append(0)
    return predictions
In [175]:
print("="*100)
from sklearn.metrics import confusion_matrix
print("Train confusion matrix")
print(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)))
print("="*100)
print("Test confusion matrix")
print(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)))
print("="*100)
====================================================================================================
Train confusion matrix
the maximum value of tpr*(1-fpr) 0.24999995727635754 for threshold 0.013
[[1210 1209]
 [4155 9137]]
====================================================================================================
Test confusion matrix
the maximum value of tpr*(1-fpr) 0.25 for threshold 0.016
[[1042  736]
 [4387 5385]]
====================================================================================================

Confusion Matrix :Heat map on Train data

In [176]:
conf_mat_BOW_train = pd.DataFrame(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_mat_BOW_train, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.24999995727635754 for threshold 0.013
Out[176]:
Text(26.5, 0.5, 'Actual Label')

Confusion Matrix :Heat map on Test data

In [177]:
conf_mat_BOW_test= pd.DataFrame(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_mat_BOW_test, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.25 for threshold 0.016
Out[177]:
Text(26.5, 0.5, 'Actual Label')

SET 2

Applying SVM on TFIDF

In [178]:
from scipy.sparse import hstack

X_train_merge = hstack((categories_one_hot_train, sub_cat_one_hot_train, school_state_one_hot_train, project_grade_cat_one_hot_train, teacher_prefix_cat_one_hot_train, price_data_train, quant_train, prev_no_projects_train,title_tfidf_train, essay_tfidf_train)).tocsr()
X_test_merge = hstack((categories_one_hot_test, sub_cat_one_hot_test, school_state_one_hot_test, project_grade_cat_one_hot_test, teacher_prefix_cat_one_hot_test, price_data_test, quant_test, prev_no_projects_test,title_tfidf_test, essay_tfidf_test)).tocsr()

print("Final Data matrix")
print("="*100)
print(X_train_merge.shape, Y_train.shape)
print(X_test_merge.shape, Y_test.shape)
print("="*100)
Final Data matrix
====================================================================================================
(15711, 5512) (15711,)
(11550, 5512) (11550,)
====================================================================================================

Best hyper prameter using the ROC/AUC higest value and K-fold cross validation.

In [179]:
from sklearn.model_selection import GridSearchCV
from sklearn import linear_model
from sklearn.linear_model import SGDClassifier

svm = SGDClassifier(class_weight='balanced')
parameters = {'loss' :['hinge'],'penalty' :["l1", "l2"],'alpha':[abs(math.log10(10**1)),abs(math.log10(10**2)),abs(math.log10(10**3)),abs(math.log10(10**4))
                       ,abs(math.log10(10**5)),abs(math.log10(10**6)),abs(math.log10(10**7))
                       ,abs(math.log10(10**8))]}

clf = GridSearchCV(svm, parameters, cv= 10, scoring='roc_auc')

grid_result = clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']

print('Best Score: ', grid_result.best_score_)
print('Best Params: ', grid_result.best_params_)
Best Score:  0.5593953504642857
Best Params:  {'alpha': 8.0, 'loss': 'hinge', 'penalty': 'l2'}

Plot the hyperparameter vs AUC curve using the best parms and best regularisation

In [180]:
svm = SGDClassifier(class_weight='balanced')

parameters = {'loss' :['hinge'],'penalty' :['l2'],'alpha':[abs(math.log10(10**1)),abs(math.log10(10**2)),abs(math.log10(10**3)),abs(math.log10(10**4))
                       ,abs(math.log10(10**5)),abs(math.log10(10**6)),abs(math.log10(10**7))
                       ,abs(math.log10(10**8))]}

clf = GridSearchCV(svm, parameters, cv= 10, scoring='roc_auc')

clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']

plt.figure(figsize=(20,10))

plt.plot(parameters['alpha'], train_auc, label='Train AUC')
plt.gca().fill_between(parameters['alpha'],train_auc - train_auc_std,train_auc + train_auc_std,alpha=0.3,color='darkblue')

plt.plot(parameters['alpha'], cv_auc, label='CV AUC')
plt.gca().fill_between(parameters['alpha'],cv_auc - cv_auc_std,cv_auc + cv_auc_std,alpha=0.3,color='darkorange')

plt.scatter(parameters['alpha'], train_auc, label='Train AUC points')
plt.scatter(parameters['alpha'], cv_auc, label='CV AUC points')


plt.legend()
plt.xlabel("Alpha: hyperparameter")
plt.ylabel("AUC")
plt.title("Alpha: hyperparameter v/s AUC plot")
plt.grid(True)
plt.show()
In [181]:
best_alpha = 100000000

#log of 10^1  =  1
#log of 10^2  =  2
#log of 10^3  =  3
#log of 10^4  =  4
#log of 10^5  =  5
#log of 10^6  =  6
#log of 10^7  =  7
#log of 10^8  =  8

Train Model using the best value of the hyper parameter

In [182]:
from sklearn.metrics import roc_curve, auc
from sklearn import linear_model
from sklearn.linear_model import SGDClassifier

svm = SGDClassifier(loss='hinge', penalty='l2',alpha = best_alpha,class_weight='balanced') #Multinominal Naive Bayes.
svm.fit(X_train_merge, Y_train)

y_train_pred = svm.decision_function(X_train_merge)    
y_test_pred = svm.decision_function(X_test_merge)

train_fpr, train_tpr, tr_thresholds = roc_curve(Y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(Y_test, y_test_pred)

plt.figure(figsize=(20,10))


plt.plot(train_fpr, train_tpr, label="Train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="Test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("True Positive Rate(TPR)")
plt.ylabel("False Positive Rate(FPR)")
plt.title("AUC")
plt.grid(True)
plt.show()

Confusion Matrix

In [183]:
print("="*100)
from sklearn.metrics import confusion_matrix
print("Train confusion matrix")
print(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)))
print("="*100)
print("Test confusion matrix")
print(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)))
print("="*100)
====================================================================================================
Train confusion matrix
the maximum value of tpr*(1-fpr) 0.24999995727635754 for threshold -0.0
[[1210 1209]
 [5388 7904]]
====================================================================================================
Test confusion matrix
the maximum value of tpr*(1-fpr) 0.25 for threshold -0.0
[[1112  666]
 [5328 4444]]
====================================================================================================

Confusion Matrix :Heat map on train data

In [184]:
conf_matr_df_tfidf_train = pd.DataFrame(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_train, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.24999995727635754 for threshold -0.0
Out[184]:
Text(26.5, 0.5, 'Actual Label')

Confusion Matrix :Heat map on test data

In [185]:
conf_matr_df_tfidf_test = pd.DataFrame(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_test, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.25 for threshold -0.0
Out[185]:
Text(26.5, 0.5, 'Actual Label')

SET 3

Applying SVM on AVG-W2V

In [186]:
from scipy.sparse import hstack

X_train_merge = hstack((categories_one_hot_train, sub_cat_one_hot_train, school_state_one_hot_train, project_grade_cat_one_hot_train, teacher_prefix_cat_one_hot_train, price_data_train, quant_train, prev_no_projects_train,title_avg_w2v_train, essay_avg_w2v_train)).tocsr()
X_test_merge = hstack((categories_one_hot_test, sub_cat_one_hot_test, school_state_one_hot_test, project_grade_cat_one_hot_test, teacher_prefix_cat_one_hot_test, price_data_test, quant_test, prev_no_projects_test,title_avg_w2v_test, essay_avg_w2v_test)).tocsr()

print("Final Data matrix")
print("="*100)
print(X_train_merge.shape, Y_train.shape)
print(X_test_merge.shape, Y_test.shape)
print("="*100)
Final Data matrix
====================================================================================================
(15711, 702) (15711,)
(11550, 702) (11550,)
====================================================================================================

Best hyper prameter using the ROC/AUC higest value and K-fold cross validation

In [187]:
from sklearn.model_selection import GridSearchCV
from sklearn import linear_model
from sklearn.linear_model import SGDClassifier

svm = SGDClassifier(class_weight='balanced')
parameters = {'loss' :['hinge'],'penalty' :["l1", "l2"],'alpha':[abs(math.log10(10**1)),abs(math.log10(10**2)),abs(math.log10(10**3)),abs(math.log10(10**4))
                       ,abs(math.log10(10**5)),abs(math.log10(10**6)),abs(math.log10(10**7))
                       ,abs(math.log10(10**8))]}

clf = GridSearchCV(svm, parameters, cv= 10, scoring='roc_auc')

grid_result = clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']


print('Best Score: ', grid_result.best_score_)
print('Best Params: ', grid_result.best_params_)
Best Score:  0.5973617409642639
Best Params:  {'alpha': 3.0, 'loss': 'hinge', 'penalty': 'l2'}

Plot the hyperparameter vs AUC curve using the best parms and best regularisation

In [188]:
svm = SGDClassifier(class_weight='balanced')

parameters = {'loss' :['hinge'],'penalty' :['l2'],'alpha':[abs(math.log10(10**1)),abs(math.log10(10**2)),abs(math.log10(10**3)),abs(math.log10(10**4))
                       ,abs(math.log10(10**5)),abs(math.log10(10**6)),abs(math.log10(10**7))
                       ,abs(math.log10(10**8))]}

clf = GridSearchCV(svm, parameters, cv= 10, scoring='roc_auc')

clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']

plt.figure(figsize=(20,10))

plt.plot(parameters['alpha'], train_auc, label='Train AUC')
plt.gca().fill_between(parameters['alpha'],train_auc - train_auc_std,train_auc + train_auc_std,alpha=0.3,color='darkblue')

plt.plot(parameters['alpha'], cv_auc, label='CV AUC')
plt.gca().fill_between(parameters['alpha'],cv_auc - cv_auc_std,cv_auc + cv_auc_std,alpha=0.3,color='darkorange')

plt.scatter(parameters['alpha'], train_auc, label='Train AUC points')
plt.scatter(parameters['alpha'], cv_auc, label='CV AUC points')


plt.legend()
plt.xlabel("Alpha: hyperparameter")
plt.ylabel("AUC")
plt.title("Alpha: hyperparameter v/s AUC plot")
plt.grid(True)
plt.show()
In [189]:
best_alpha = 1000

#log of 10^1  =  1
#log of 10^2  =  2
#log of 10^3  =  3
#log of 10^4  =  4
#log of 10^5  =  5
#log of 10^6  =  6
#log of 10^7  =  7
#log of 10^8  =  8

Train the model using the best hyperparameter

In [190]:
from sklearn.metrics import roc_curve, auc
from sklearn import linear_model
from sklearn.linear_model import SGDClassifier

svm = SGDClassifier(loss='hinge', penalty='l1',alpha = best_alpha,class_weight='balanced') #Multinominal Naive Bayes.
svm.fit(X_train_merge, Y_train)


y_train_pred = svm.decision_function(X_train_merge)    
y_test_pred = svm.decision_function(X_test_merge)

train_fpr, train_tpr, tr_thresholds = roc_curve(Y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(Y_test, y_test_pred)

plt.figure(figsize=(20,10))

plt.plot(train_fpr, train_tpr, label="Train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="Test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("True Positive Rate(TPR)")
plt.ylabel("False Positive Rate(FPR)")
plt.title("AUC")
plt.grid(True)
plt.show()

Confusion Matrix

In [191]:
print("="*100)
from sklearn.metrics import confusion_matrix
print("Train confusion matrix")
print(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)))
print("="*100)
print("Test confusion matrix")
print(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)))
print("="*100)
====================================================================================================
Train confusion matrix
the maximum value of tpr*(1-fpr) 0.0 for threshold 1.001
[[ 2419     0]
 [13292     0]]
====================================================================================================
Test confusion matrix
the maximum value of tpr*(1-fpr) 0.0 for threshold 1.001
[[1778    0]
 [9772    0]]
====================================================================================================

Confusion Matrix: Heat map on Train data

In [192]:
conf_matr_df_tfidf_train = pd.DataFrame(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_train, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.0 for threshold 1.001
Out[192]:
Text(26.5, 0.5, 'Actual Label')

Confusion Matrix: Heat map on Test data

In [193]:
conf_matr_df_tfidf_test = pd.DataFrame(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_test, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.0 for threshold 1.001
Out[193]:
Text(26.5, 0.5, 'Actual Label')

SET 4

Applying SVM on AVG-W2V

In [195]:
from scipy.sparse import hstack

X_train_merge = hstack((categories_one_hot_train, sub_cat_one_hot_train, school_state_one_hot_train, project_grade_cat_one_hot_train, teacher_prefix_cat_one_hot_train, price_data_train, quant_train, prev_no_projects_train,title_tfidf_w2v_train, essay_tfidf_w2v_train)).tocsr()
X_test_merge = hstack((categories_one_hot_test, sub_cat_one_hot_test, school_state_one_hot_test, project_grade_cat_one_hot_test, teacher_prefix_cat_one_hot_test, price_data_test, quant_test, prev_no_projects_test,title_tfidf_w2v_test, essay_tfidf_w2v_test)).tocsr()

print("Final Data matrix")
print("="*100)
print(X_train_merge.shape, Y_train.shape)
print(X_test_merge.shape, Y_test.shape)
print("="*100)
Final Data matrix
====================================================================================================
(15711, 702) (15711,)
(11550, 702) (11550,)
====================================================================================================

Best hyper prameter using the ROC/AUC higest value and K-fold cross validation

In [196]:
from sklearn.model_selection import GridSearchCV
from sklearn import linear_model
from sklearn.linear_model import SGDClassifier

svm = SGDClassifier(class_weight='balanced')
parameters = {'loss' :['hinge'],'penalty' :["l1", "l2"],'alpha':[abs(math.log10(10**1)),abs(math.log10(10**2)),abs(math.log10(10**3)),abs(math.log10(10**4))
                       ,abs(math.log10(10**5)),abs(math.log10(10**6)),abs(math.log10(10**7))
                       ,abs(math.log10(10**8))]}

clf = GridSearchCV(svm, parameters, cv= 10, scoring='roc_auc')

grid_result = clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']


print('Best Score: ', grid_result.best_score_)
print('Best Params: ', grid_result.best_params_)
Best Score:  0.5573632745275447
Best Params:  {'alpha': 1.0, 'loss': 'hinge', 'penalty': 'l2'}

Plot the hyperparameter vs AUC curve using the best parms and best regularisation

In [197]:
svm = SGDClassifier(class_weight='balanced')

parameters = {'loss' :['hinge'],'penalty' :['l2'],'alpha':[abs(math.log10(10**1)),abs(math.log10(10**2)),abs(math.log10(10**3)),abs(math.log10(10**4))
                       ,abs(math.log10(10**5)),abs(math.log10(10**6)),abs(math.log10(10**7))
                       ,abs(math.log10(10**8))]}

clf = GridSearchCV(svm, parameters, cv= 10, scoring='roc_auc')

clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']

plt.figure(figsize=(20,10))

plt.plot(parameters['alpha'], train_auc, label='Train AUC')
plt.gca().fill_between(parameters['alpha'],train_auc - train_auc_std,train_auc + train_auc_std,alpha=0.3,color='darkblue')

plt.plot(parameters['alpha'], cv_auc, label='CV AUC')
plt.gca().fill_between(parameters['alpha'],cv_auc - cv_auc_std,cv_auc + cv_auc_std,alpha=0.3,color='darkorange')

plt.scatter(parameters['alpha'], train_auc, label='Train AUC points')
plt.scatter(parameters['alpha'], cv_auc, label='CV AUC points')


plt.legend()
plt.xlabel("Alpha: hyperparameter")
plt.ylabel("AUC")
plt.title("Alpha: hyperparameter v/s AUC plot")
plt.grid(True)
plt.show()
In [198]:
best_alpha = 10

#log of 10^1  =  1
#log of 10^2  =  2
#log of 10^3  =  3
#log of 10^4  =  4
#log of 10^5  =  5
#log of 10^6  =  6
#log of 10^7  =  7
#log of 10^8  =  8

Train the model using the best Hyperparameter

In [199]:
from sklearn.metrics import roc_curve, auc
from sklearn import linear_model
from sklearn.linear_model import SGDClassifier

svm = SGDClassifier(loss='hinge', penalty='l2',alpha = best_alpha,class_weight='balanced') #Multinominal Naive Bayes.
svm.fit(X_train_merge, Y_train)

y_train_pred = svm.decision_function(X_train_merge)    
y_test_pred = svm.decision_function(X_test_merge)

train_fpr, train_tpr, tr_thresholds = roc_curve(Y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(Y_test, y_test_pred)

plt.figure(figsize=(20,10))


plt.plot(train_fpr, train_tpr, label="Train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="Test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("True Positive Rate(TPR)")
plt.ylabel("False Positive Rate(FPR)")
plt.title("AUC")
plt.grid(True)
plt.show()

Confusion Matrix

In [200]:
print("="*100)
from sklearn.metrics import confusion_matrix
print("Train confusion matrix")
print(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)))
print("="*100)
print("Test confusion matrix")
print(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)))
print("="*100)
====================================================================================================
Train confusion matrix
the maximum value of tpr*(1-fpr) 0.24999995727635754 for threshold 0.007
[[1210 1209]
 [5497 7795]]
====================================================================================================
Test confusion matrix
the maximum value of tpr*(1-fpr) 0.25 for threshold 0.008
[[1045  733]
 [4916 4856]]
====================================================================================================

Confusion Matrix:HeatMap on Train data

In [201]:
conf_matr_df_tfidf_train = pd.DataFrame(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_train, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.24999995727635754 for threshold 0.007
Out[201]:
Text(26.5, 0.5, 'Actual Label')

Confusion Matrix: HeatMap on Test data

In [202]:
conf_matr_df_tfidf_test = pd.DataFrame(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_test, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.25 for threshold 0.008
Out[202]:
Text(26.5, 0.5, 'Actual Label')

SET 5

Apply TruncatedSVD on TfidfVectorizer of essay text, choose the number of components (n_components) using elbow method : numerical data

In [203]:
#https://www.kaggle.com/rahulpatel11315/selecting-the-best-number-of-components-for-tsvd

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import TruncatedSVD
from scipy.sparse import csr_matrix
In [204]:
essay_tfidf_train.shape
Out[204]:
(15711, 5000)
In [205]:
data=essay_tfidf_train
In [206]:
data.shape
Out[206]:
(15711, 5000)
In [207]:
# Make sparse matrix
X_sparse = csr_matrix(data)
In [208]:
data.shape[1]-1
Out[208]:
4999
In [209]:
# Create and run an TSVD with one less than number of features
tsvd = TruncatedSVD(n_components=X_sparse.shape[1]-1)
X_tsvd = tsvd.fit(data)
In [210]:
tsvd_var_ratios = tsvd.explained_variance_ratio_
In [211]:
# Create a function
def select_n_components(var_ratio, goal_var: float) -> int:
    # Set initial variance explained so far
    total_variance = 0.0
    
    # Set initial number of features
    n_components = 0
    
    # For the explained variance of each feature:
    for explained_variance in var_ratio:
        
        # Add the explained variance to the total
        total_variance += explained_variance
        
        # Add one to the number of components
        n_components += 1
        
        # If we reach our goal level of explained variance
        if total_variance >= goal_var:
            # End the loop
            break
            
    # Return the number of components
    return n_components
In [212]:
# Run function
select_n_components(tsvd_var_ratios, 0.95)
Out[212]:
3843
In [213]:
tsvd = TruncatedSVD(n_components= 3843)
tsvd.fit(essay_tfidf_train)

tsvd_essay_train = tsvd.transform(essay_tfidf_train)
tsvd_essay_test = tsvd.transform(essay_tfidf_test)

print("Shape-Essay Train after TruncatedSVD",tsvd_essay_train.shape)
print("Shape-Essay Train after TruncatedSVD",tsvd_essay_test.shape)
Shape-Essay Train after TruncatedSVD (15711, 3843)
Shape-Essay Train after TruncatedSVD (11550, 3843)
In [214]:
from scipy.sparse import hstack

X_train_merge = hstack((categories_one_hot_train, sub_cat_one_hot_train, school_state_one_hot_train, project_grade_cat_one_hot_train, teacher_prefix_cat_one_hot_train, price_data_train, quant_train, prev_no_projects_train,title_cnt_train,essay_cnt_train,essay_neg_train,essay_pos_train,essay_neu_train,essay_compound_train,tsvd_essay_train)).tocsr()
X_test_merge = hstack((categories_one_hot_test, sub_cat_one_hot_test, school_state_one_hot_test, project_grade_cat_one_hot_test, teacher_prefix_cat_one_hot_test, price_data_test, quant_test, prev_no_projects_test,title_cnt_test,essay_cnt_test,essay_neg_test,essay_pos_test,essay_neu_test,essay_compund_test,tsvd_essay_test)).tocsr()

print("Final Data matrix")
print("="*100)
print(X_train_merge.shape, Y_train.shape)
print(X_test_merge.shape, Y_test.shape)
print("="*100)
Final Data matrix
====================================================================================================
(15711, 3951) (15711,)
(11550, 3951) (11550,)
====================================================================================================
In [215]:
from sklearn.model_selection import GridSearchCV
from sklearn import linear_model
from sklearn.linear_model import SGDClassifier

svm = SGDClassifier(class_weight = 'balanced')
parameters = {'loss' :['hinge'],'penalty' :["l1", "l2"],'alpha':[abs(math.log10(10**1)),abs(math.log10(10**2)),abs(math.log10(10**3)),abs(math.log10(10**4))
                       ,abs(math.log10(10**5)),abs(math.log10(10**6)),abs(math.log10(10**7))
                       ,abs(math.log10(10**8))]}

clf = GridSearchCV(svm, parameters, cv= 10, scoring='roc_auc')

grid_result = clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']


print('Best Score: ', grid_result.best_score_)
print('Best Params: ', grid_result.best_params_)
Best Score:  0.5588580396301702
Best Params:  {'alpha': 2.0, 'loss': 'hinge', 'penalty': 'l2'}
In [216]:
svm = SGDClassifier(class_weight = 'balanced')

parameters = {'loss' :['hinge'],'penalty' :['l2'],'alpha':[abs(math.log10(10**1)),abs(math.log10(10**2)),abs(math.log10(10**3)),abs(math.log10(10**4))
                       ,abs(math.log10(10**5)),abs(math.log10(10**6)),abs(math.log10(10**7))
                       ,abs(math.log10(10**8))]}

clf = GridSearchCV(svm, parameters, cv= 10, scoring='roc_auc')

clf.fit(X_train_merge,Y_train)

train_auc= clf.cv_results_['mean_train_score']
train_auc_std= clf.cv_results_['std_train_score']
cv_auc = clf.cv_results_['mean_test_score'] 
cv_auc_std= clf.cv_results_['std_test_score']

plt.figure(figsize=(20,10))

plt.plot(parameters['alpha'], train_auc, label='Train AUC')
plt.gca().fill_between(parameters['alpha'],train_auc - train_auc_std,train_auc + train_auc_std,alpha=0.3,color='darkblue')

plt.plot(parameters['alpha'], cv_auc, label='CV AUC')
plt.gca().fill_between(parameters['alpha'],cv_auc - cv_auc_std,cv_auc + cv_auc_std,alpha=0.3,color='darkorange')

plt.scatter(parameters['alpha'], train_auc, label='Train AUC points')
plt.scatter(parameters['alpha'], cv_auc, label='CV AUC points')


plt.legend()
plt.xlabel("Alpha: hyperparameter")
plt.ylabel("AUC")
plt.title("Alpha: hyperparameter v/s AUC plot")
plt.grid(True)
plt.show()
In [217]:
best_alpha=100
In [218]:
from sklearn.metrics import roc_curve, auc
from sklearn import linear_model
from sklearn.linear_model import SGDClassifier

svm = SGDClassifier(loss='hinge', penalty='l2',alpha = best_alpha,class_weight = 'balanced') 
svm.fit(X_train_merge, Y_train)

y_train_pred = svm.decision_function(X_train_merge)    
y_test_pred = svm.decision_function(X_test_merge)

plt.figure(figsize=(20,10))


train_fpr, train_tpr, tr_thresholds = roc_curve(Y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(Y_test, y_test_pred)

plt.plot(train_fpr, train_tpr, label="Train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="Test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("True Positive Rate(TPR)")
plt.ylabel("False Positive Rate(FPR)")
plt.title("AUC")
plt.grid(True)
plt.show()
In [219]:
print("="*100)
from sklearn.metrics import confusion_matrix
print("Train confusion matrix")
print(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)))
print("="*100)
print("Test confusion matrix")
print(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)))
print("="*100)
====================================================================================================
Train confusion matrix
the maximum value of tpr*(1-fpr) 0.24999995727635754 for threshold 0.002
[[1210 1209]
 [5425 7867]]
====================================================================================================
Test confusion matrix
the maximum value of tpr*(1-fpr) 0.24999968367283673 for threshold 0.002
[[1140  638]
 [5447 4325]]
====================================================================================================
In [220]:
conf_matr_df_tfidf_train = pd.DataFrame(confusion_matrix(Y_train, predict(y_train_pred, tr_thresholds, train_fpr, train_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_train, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.24999995727635754 for threshold 0.002
Out[220]:
Text(26.5, 0.5, 'Actual Label')
In [221]:
conf_matr_df_tfidf_test = pd.DataFrame(confusion_matrix(Y_test, predict(y_test_pred, tr_thresholds, test_fpr, test_fpr)), range(2),range(2))
sns.set(font_scale=1.4)
sns.heatmap(conf_matr_df_tfidf_test, annot=True,annot_kws={"size": 16}, fmt='g')
plt.xlabel("Predicted Label")
plt.ylabel("Actual Label")
the maximum value of tpr*(1-fpr) 0.24999968367283673 for threshold 0.002
Out[221]:
Text(26.5, 0.5, 'Actual Label')

Conclusion

In [222]:
from prettytable import PrettyTable

x_pretty_table = PrettyTable()
x_pretty_table.field_names = ["Model Type","Vectorizer","Alpha", "Penalty","Train-AUC","Test-AUC"]

x_pretty_table.add_row(["SVM","BOW",10,"l2",0.64,0.60])
x_pretty_table.add_row([ "SVM","TFIDF",100000000,"l2",0.57,0.56])
x_pretty_table.add_row([ "SVM","AVG W2V",1000,"l2",0.5,.5])
x_pretty_table.add_row([ "SVM","TFIDF W2V",10,"l2",0.56,0.55])
x_pretty_table.add_row([ "SVM","TruncatedSVD",100,"l2",0.57,0.56])

print(x_pretty_table)
+------------+--------------+-----------+---------+-----------+----------+
| Model Type |  Vectorizer  |   Alpha   | Penalty | Train-AUC | Test-AUC |
+------------+--------------+-----------+---------+-----------+----------+
|    SVM     |     BOW      |     10    |    l2   |    0.64   |   0.6    |
|    SVM     |    TFIDF     | 100000000 |    l2   |    0.57   |   0.56   |
|    SVM     |   AVG W2V    |    1000   |    l2   |    0.5    |   0.5    |
|    SVM     |  TFIDF W2V   |     10    |    l2   |    0.56   |   0.55   |
|    SVM     | TruncatedSVD |    100    |    l2   |    0.57   |   0.56   |
+------------+--------------+-----------+---------+-----------+----------+
In [ ]: